package com.cy.store.service.impl;

import com.cy.store.entity.Address;
import com.cy.store.mapper.AddressMapper;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IDistrictService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 新增地址的实现类
 */
@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    //在添加收货地址的业务层依赖于DistrictService的业务层接口
    @Autowired
    private IDistrictService districtService;

    @Value("${user.address.max-count}")
    private Integer maxCount;

    /**
     * 修改用户某个收货地址为默认地址
     *
     * @param aid
     * @param uid
     * @param username
     */
    @Override
    public void setDefault(Integer aid, Integer uid, String username) {
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressNotFoundException("收货地址不存在");
        }
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("非法访问");
        }
        // 先将用户的所有收获地址设置为非默认
        Integer rows = addressMapper.updateNonDefault(uid);
        if (rows < 1) {
            throw new UpdateException("更新异常");
        }

        rows = addressMapper.updateDefaultByAid(aid, username, new Date());
        if (rows != 1) {
            throw new UpdateException("更新异常");
        }
    }

    /**
     * 通过用户id获取收货地址
     *
     * @param uid
     * @return
     */
    @Override
    public List<Address> getByUid(Integer uid) {
        List<Address> addressList = addressMapper.findByUid(uid);
        addressList = addressList.stream().map((item) -> {
//            item.setAid(null);
//            item.setUid(null);
            item.setProvinceCode(null);
            item.setCityCode(null);
            item.setAreaCode(null);
            item.setZip(null);
            item.setTel(null);
            item.setCreatedTime(null);
            item.setCreatedUser(null);
            item.setModifiedTime(null);
            item.setModifiedUser(null);
            return item;
        }).collect(Collectors.toList());
        return addressList;
    }

    /**
     * 删除收货地址
     *
     * @param aid
     * @param uid
     * @param username
     */
    @Override
    public void delete(Integer aid, Integer uid, String username) {
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressNotFoundException("收货地址数据异常");
        }
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("非法访问数据");
        }
        Integer rows = addressMapper.deleteByAid(aid);
        if (rows != 1) {
            throw new DeleteException("删除异常");
        }

        Integer count = addressMapper.countByUid(uid);
        //如果此时已经没有收货地址则直接结束
        if (count == 0) {
            return;
        }

        //如果删除的地址为默认地址，则将最新修改的地址设置为默认地址
        if (address.getIsDefault() == 1) {
            Address lastModified = addressMapper.findLastModified(uid);
            //调用该类中的setDefault方法进行重新设置默认地址
            this.setDefault(lastModified.getAid(), uid, username);
        }

    }

    /**
     * 用aid查询收货地址
     *
     * @param aid
     * @return
     */
    @Override
    public Address findByAid(Integer aid, Integer uid) {
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressNotFoundException("数据不存在");
        } else if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("数据非法访问");
        }
        //重新封装查询结果
        address.setUid(null);
        address.setCreatedUser(null);
        address.setCreatedTime(null);
        address.setModifiedTime(null);
        address.setModifiedUser(null);

        return address;
    }

    /**
     * 修改收货地址
     *
     * @param aid
     * @param uid
     * @param address
     * @param username
     */
    @Override
    public void update(Integer aid, Integer uid, Address address, String username) {
        //先确定修改的是不是为空 或 非自己的地址
        Address result = addressMapper.findByAid(aid);
        if (result == null) {
            throw new AddressNotFoundException("数据不存在");
        }
        if (!result.getUid().equals(uid)) {
            throw new AccessDeniedException("数据非法访问");
        }

        //获取收货地址的省市区信息并填充到收货地址中
        String proviceName = districtService.getNameByCode(address.getProvinceCode());
        String cityName = districtService.getNameByCode(address.getCityCode());
        String areaName = districtService.getNameByCode(address.getAreaCode());

        address.setProvinceName(proviceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);

        //补全日志
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());

        //补充aid
        address.setAid(aid);

        Integer rows = addressMapper.updateAddress(address);

        if (rows != 1) {
            throw new UpdateException("修改信息异常");
        }
    }

    /**
     * 添加收货地址
     *
     * @param uid
     * @param username
     * @param address
     */
    @Override
    public void addNewAddress(Integer uid, String username, Address address) {
        Integer count = addressMapper.countByUid(uid);
        if (count >= maxCount) {
            throw new AddressCountLimitException("收货地址数量过多，已无法继续添加");
        }

        //对address对象中的数据进行补全：省市区的相关数据
        String proviceName = districtService.getNameByCode(address.getProvinceCode());
        String cityName = districtService.getNameByCode(address.getCityCode());
        String areaName = districtService.getNameByCode(address.getAreaCode());

        address.setProvinceName(proviceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);


        address.setUid(uid);

        Integer isDefault = count == 0 ? 1 : 0;//1表示默认
        address.setIsDefault(isDefault);

        //补全日志
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());

        Integer rows = addressMapper.insert(address);
        if (rows != 1) {
            throw new InsertException("添加异常");
        }
    }
}
